# -*- coding: utf-8 -*-
"""
Python代码示例
"""
import base64
import datetime
from hashlib import sha1
import hmac
import json 
import time

import requests

# openapi地址
OPENAPI_BASE_URL = "https://api.su.baidu.com/%s"

ACCESS_KEY = "35f8a943622d4bc0bab04a428b0f262d"
SECRET_KEY = "7705152a2dec44388467bb80f676b491"

# 签名算法
SIGN_METHOD = "HMAC-SHA1"


def get_signature(sec_key, text):
    """
    计算签名
    """
    hmac_code = hmac.new(sec_key.encode(), text.encode(), sha1).digest()
    return base64.b64encode(hmac_code).decode()




def get_inited_common_params(path):
    """
    获取通用参数
    """
    param_map = {}

    auth_timestamp = str(int(time.time()))
    param_map['X-Auth-Access-Key'] = ACCESS_KEY
    param_map['X-Auth-Nonce'] = auth_timestamp
    param_map['X-Auth-Path-Info'] = path
    param_map['X-Auth-Signature-Method'] = SIGN_METHOD
    param_map['X-Auth-Timestamp'] = auth_timestamp

    return param_map


def smart_str(target_string):
    """
    处理字符串
    """
    if isinstance(target_string, bytes):
        return target_string.encode("utf-8")
    elif isinstance(target_string, str):
        return target_string
    
    return json.dumps(target_string)


def get_parsed_all_params(params):
    """
    拼接参数
    """
    keys = params.keys()
    sorted(keys)
    return "&".join(["%s=%s" % (str(k), smart_str(params[k])) for k in keys])

# 获取请求头
def get_request_header(path, query_params, body_params):
    """
    获取请求的Header
    """
    common_params = get_inited_common_params(path)
    all_params = {}
    headers = {}

    headers.update(common_params)

    all_params.update(common_params)
    all_params.update(query_params)
    all_params.update(body_params)

    all_params_str = get_parsed_all_params(all_params)

    sign = get_signature(SECRET_KEY, all_params_str)

    headers["X-Auth-Sign"] = sign

    return headers


def send_http_request(method='GET', url='', params=None, payload=None, headers=None):
    """
    发送Http请求
    """
    if params is None:
        params = {}
    if payload is None:
        payload = {}
    if headers is None:
        headers = {}
    '''   
    print '%s:%s' % (method, url)
    print 'Params:%s' % json.dumps(params, indent=4)
    print 'Payload:%s' % json.dumps(payload, indent=4)
    print 'Headers:%s' % json.dumps(headers, indent=4)
    '''
    print('%s:%s' % (method, url))
    print('Params:%s' % json.dumps(params, indent=4))
    print('Payload:%s' % json.dumps(payload, indent=4))
    print('Headers:%s' % json.dumps(headers, indent=4))
        
    resp = requests.request(method, url, params=params, data=json.dumps(payload), headers=headers)
    
    print(('Response:%s') % json.dumps(json.loads(resp.text), indent=4))
    
    return resp


def hotlink_protection():
    """
    示例
    """
    path = "v31/yjs/zones/5fb63643aca300429d044a43/settings/hotlink_protection"
    params = {}

    payload = {}
    payload['value'] = {"allowed_hostnames": ["*.baidu.com", "*.cloudflare.coms"], "status": "on"}
    # payload['value'] = {"status": "on", "allowed_hostnames": ["*.baidu.com", "*.cloudflare.coms"]}

    headers = get_request_header(path, params, payload)

    url = OPENAPI_BASE_URL % path
    
    response = send_http_request("PATCH", url, params=params, payload=payload, headers=headers)

    
if __name__ == '__main__':
    hotlink_protection()
    # sign = get_signature("456789", "123456")
    # print(sign)


